package com.quectel.cms.controller.pet;

import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.interceptor.LoginUserSession;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.pet.dto.PetDto;
import com.quectel.core.module.pet.service.PetService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/11/08 16:25
 */
@RestController
@RequestMapping("pet")
@Tag(name = "PetController", description = "宠物相关api 请开发者检查描述")
public class PetController extends BaseController {

    @DubboReference
    private PetService petService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private VillageRoomService villageRoomService;

    /**
     * 导入宠物信息
     */
    @PostMapping("importExcel")
    @RequirePermissions(values = "pet:import")
    @Operation(summary = "导入宠物信息")
    @Log(express = "导入宠物信息")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {
        LoginUserSession sysUser = SessionHolder.getSysUser();
        assert sysUser != null;

        Map<String, VillageDto> villageCache = new HashMap<>();
        Map<String, VillageBuildingDto> buildingCache = new HashMap<>();
        Map<String, VillageRoomDto> roomCache = new HashMap<>();

        List<PetDto> list = new ArrayList<>();

        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                try {
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);
                    for (Map<Integer, String> map : analysis) {
                        try {
                            if (StringUtils.isBlank(map.get(3)) || StringUtils.isBlank(map.get(4))
                                    || StringUtils.isBlank(map.get(5)) || StringUtils.isBlank(map.get(6))) {
                                // 3养宠人姓名 4养宠人手机 5宠物名称 6宠物种类
                                continue;
                            }

                            VillageDto villageDto = villageCache.computeIfAbsent(map.get(0), s -> villageService.selectByName(sysUser.getTenantId(), s));
                            if (villageDto == null) {
                                continue;
                            }
                            VillageBuildingDto villageBuildingDto = buildingCache.computeIfAbsent(villageDto.getId() + "_" + map.get(1), s -> {
                                String[] sSplit = s.split("_");
                                return villageBuildingService.selectByName(Long.valueOf(sSplit[0]), sSplit[1]);
                            });
                            if (villageBuildingDto == null) {
                                continue;
                            }
                            VillageRoomDto villageRoomDto = roomCache.computeIfAbsent(villageBuildingDto.getId() + "_" + map.get(2), s -> {
                                String[] sSplit = s.split("_");
                                return villageRoomService.selectByNameWithBuildingId(Long.valueOf(sSplit[0]), sSplit[1]);
                            });
                            if (villageRoomDto == null) {
                                continue;
                            }

                            PetDto petDto = new PetDto();
                            petDto.setTenantId(sysUser.getTenantId());
                            petDto.setVillageId(villageDto.getId());
                            petDto.setBuildingId(villageRoomDto.getBuildingId());
                            petDto.setFloorId(villageRoomDto.getFloorId());
                            petDto.setRoomId(villageRoomDto.getId());
                            petDto.setOwnerName(map.get(3));
                            petDto.setOwnerMobile(map.get(4));
                            petDto.setPetName(map.get(5));
                            petDto.setPetType(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.PET_TYPE, map.get(6), Byte.class));
                            petDto.setPetBreed(map.get(7));
                            try {
                                Date parse = DateUtils.parse(map.get(8), DateUtils.FormatType.SIMPLE);
                                petDto.setBirthDate(parse);
                            } catch (Exception e) {
                                logger.debug("解析宠物生日错误 ", e);
                            }
                            petDto.setGender(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.PET_GENDER, map.get(9), Byte.class));
                            petDto.setLicenseNumber(map.get(10));
                            try {
                                Date parse = DateUtils.parse(map.get(11), DateUtils.FormatType.SIMPLE);
                                petDto.setCertificationTime(parse);
                            } catch (Exception e) {
                                logger.debug("解析取证日期错误 ", e);
                            }
                            try {
                                Date parse = DateUtils.parse(map.get(12), DateUtils.FormatType.COMMON);
                                petDto.setLastVaccineDate(parse);
                            } catch (Exception e) {
                                logger.debug("解析最新疫苗时间错误 ", e);
                            }
                            list.add(petDto);

                        } catch (Exception e) {
                            logger.error("读取宠物信息错误 ", e);
                        }
                    }
                } catch (Exception e) {
                    logger.error("解析导入信息出错");
                }
            }
        }

        petService.saveBatch(list);
        int successCount = list.size();
        return Response.error("导入成功,导入成功数量为:" + successCount + "，数量少于导入数量，请检查必填信息");
    }

    /**
     * 导出宠物信息
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "pet:export")
    @Operation(summary = "导出宠物信息")
    @Log(express = "导出宠物信息")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<PetDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<PetDto> list = petService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "所属楼栋", "所属房屋", "养宠人姓名", "养宠人电话", "宠物名称", "宠物类别", "宠物性别", "出生日期", "许可证号"};
        List<String[]> dataList = new ArrayList<>();
        for (PetDto data : result) {
            String[] item = new String[headers.length];
            item[0] = Objects.nonNull(data.getVillage()) ? data.getVillage().getName() : "";
            item[1] = data.getVillageRoom() != null ? data.getVillageRoom().getBuildingName() : "";
            item[2] = data.getVillageRoom() != null ? data.getVillageRoom().getName() : "";
            item[3] = data.getOwnerName();
            item[4] = data.getOwnerMobile();
            item[5] = data.getPetName();
            item[6] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PET_TYPE, data.getPetType() + "") + " - " + data.getPetBreed();
            item[7] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PET_GENDER, data.getGender() + "");
            item[8] = data.getBirthDate() != null ? DateUtils.format(data.getBirthDate(), DateUtils.FormatType.SIMPLE) : "";
            item[9] = data.getLicenseNumber();
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "宠物信息", headers, dataList, "宠物信息");
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "pet:list")
    @Operation(summary = "分页获取宠物列表 请开发者检查描述")
    public Response<Page<PetDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = petService.queryTotal(request.getParams());

        List<PetDto> list = null;
        if (total > 0) {
            list = petService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<PetDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<PetDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "pet:edit")
    @Operation(summary = "在编辑时根据id查询宠物详情 请开发者检查描述")
    public Response<PetDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (petService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PetDto petDto = petService.selectById(id);

        return Response.<PetDto>ok().wrap(petDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "pet:info")
    @Operation(summary = "根据id查询宠物的详情 请开发者检查描述")
    public Response<PetDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (petService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PetDto petDto = petService.selectById(id);

        return Response.<PetDto>ok().wrap(petDto);
    }

    /**
     * 保存
     *
     * @param petDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "pet:edit")
    @Operation(summary = "新增宠物 请开发者检查描述")
    public Response<Object> save(@RequestBody @Validated PetDto petDto) {
        VillageRoomDto villageRoomDto = villageRoomService.selectCacheById(petDto.getRoomId());
        if (villageRoomDto == null) {
            return Response.error("房屋不存在");
        }
        petDto.setBuildingId(villageRoomDto.getBuildingId());
        petDto.setFloorId(villageRoomDto.getFloorId());

        //填充基础数据
        fillSaveCommonData(petDto);

        petService.save(petDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param petDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "pet:edit")
    @Operation(summary = "根据id修改宠物 请开发者检查描述")
    public Response<Object> update(@RequestBody  @Validated PetDto petDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(petDto.getId()));
        if (petService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(petDto);

        petService.updateById(petDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "pet:delete")
    @Operation(summary = "根据多条记录id批量删除宠物 请开发者检查描述")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (petService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        petService.deleteBatch(ids);

        return Response.ok();
    }
}
